package com.cjh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjh.entity.User;
import com.cjh.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 使用数据库查询来做登录
 */
@Service("myUserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",userName);

        //如果有权限业务，可以根据userid去查询权限再set进user
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)){
            //如果不存在用户，必须new一个再返回，不然报异常
            return new User();
        }
        return user;
    }
}
